using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteAlways]
public class GlobalShaderPos : MonoBehaviour
{
    [Range(0, 10)] public float archWorldRadius = 3;
    // [Range(0, 60)] public int maxCount = 32;
    [Range(0, 10)] public float archRadiusDebugVis = 1;
    private ComputeBuffer posesRadiusBuffer; // 用于存储世界位置数据

  
    // Update is called once per frame
    void Update()
    {
        var posesRadius = new List<Vector4>();
        var posesRadiusBufferData = new List<float>();
        foreach (Transform child in transform)
        {
            Vector3 pos = child.position;
            posesRadius.Add(new Vector4(pos.x, pos.y, pos.z, archWorldRadius));
            posesRadiusBufferData.Add(pos.x);
            posesRadiusBufferData.Add(pos.y);
            posesRadiusBufferData.Add(pos.z);
            posesRadiusBufferData.Add(archWorldRadius);
        }

        if (posesRadiusBuffer != null)
        {
            posesRadiusBuffer.Release();
        }

        // 创建一个新的 ComputeBuffer, 传递数据
        posesRadiusBuffer = new ComputeBuffer(posesRadiusBufferData.Count, sizeof(float));
        posesRadiusBuffer.SetData(posesRadiusBufferData.ToArray());

        Shader.SetGlobalInt("_ArchWorldCount", posesRadius.Count);
        Shader.SetGlobalBuffer("_ArchWorldDataArray", posesRadiusBuffer);
        Shader.SetGlobalFloat("_ArchRadiusDebugVis", archRadiusDebugVis);

        // Debug.Log("posesRadiusBuffer"+posesRadiusBuffer);
    }

    // 在销毁时释放 ComputeBuffer
    void OnDestroy()
    {
        if (posesRadiusBuffer != null)
        {
            posesRadiusBuffer.Release();
        }
    }

    // 确保在禁用时释放资源
    void OnDisable()
    {
        if (posesRadiusBuffer != null)
        {
            posesRadiusBuffer.Release();
        }
    }
}